package com.lagou.mr.mapJoin;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class MapJoinMapper extends Mapper<LongWritable, Text,Text, NullWritable> {
    Map<String,String> pMap = new HashMap<>();
    //读取文件
    @Override
    protected void setup(Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
        //获取缓存文件
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("D:/cache/hadoop/data/MRjoin/map_join/cache/position.txt"), "UTF-8"));
        String line;
        while( StringUtils.isNotEmpty(line = reader.readLine()) ){
            //切割
            String[] fields = line.split("\t");
            //缓存数据集合
            pMap.put(fields[0],fields[1]);
        }
        reader.close();
    }

    Text k = new Text();
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
        String[] fields = value.toString().split("\t");
        //获取职位ID
        String pId = fields[1];
        //获取职位名称
        String pName = pMap.get(pId);
        //拼接
        k.set(value.toString()+"\t"+pName);
        context.write(k,NullWritable.get());
    }
}
